// import uuid from 'node-uuid';

const express = require('express');
const router = express.Router();
const jwt = require("jsonwebtoken");
const config = require('../config');
const pool = require('../db');

// 登录接口
router.post("/login", (req, res) => {
  console.log('登录请求参数:', req.body);
  
  const { username, password } = req.body;
  
  if (!username || !password) {
    return res.status(400).json({
      code: 400,
      msg: "用户名和密码为必传参数"
    });
  }
  
  // 使用连接池查询用户
  const sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
  
  pool.query(sql, [username, password], (err, results) => {
    if (err) {
      console.error('数据库查询错误:', err);
      return res.status(500).json({
        code: 500,
        msg: "服务器内部错误",
        error: config.env === 'development' ? err.message : undefined
      });
    }
    
    if (results.length > 0) {
      const user = results[0];
      
      // 生成JWT token
      const token = jwt.sign(
        {
          userId: user.id,
          username: user.username,
          identity: 'user'
        },
        config.jwt.secret,
        { expiresIn: config.jwt.expiresIn }
      );
      
      res.json({
        code: 200,
        msg: "登录成功",
        data: {
          token,
          userInfo: {
            id: user.id,
            username: user.username,
            email: user.email
          }
        }
      });
    } else {
      res.status(401).json({
        code: 401,
        msg: "用户名或密码错误"
      });
    }
  });
});

// 注册接口
router.post("/register", (req, res) => {
  const { username, password, email } = req.body;
  
  if (!username || !password) {
    return res.status(400).json({
      code: 400,
      msg: "用户名和密码为必传参数"
    });
  }
  
  // 检查用户是否已存在
  const checkSql = 'SELECT id FROM users WHERE username = ?';
  
  pool.query(checkSql, [username], (err, results) => {
    if (err) {
      console.error('检查用户存在性错误:', err);
      return res.status(500).json({
        code: 500,
        msg: "服务器内部错误"
      });
    }
    
    if (results.length > 0) {
      return res.status(400).json({
        code: 400,
        msg: "用户名已存在"
      });
    }
    
    // 创建新用户
    const insertSql = 'INSERT INTO users (username, password, email) VALUES (?, ?, ?)';
    
    pool.query(insertSql, [username, password, email], (err, result) => {
      if (err) {
        console.error('创建用户错误:', err);
        return res.status(500).json({
          code: 500,
          msg: "服务器内部错误"
        });
      }
      
      res.json({
        code: 200,
        msg: "注册成功",
        data: {
          id: result.insertId,
          username,
          email
        }
      });
    });
  });
});

module.exports = router;
